<?php

namespace app\common\model;

use app\common\model\mall\Coupon;
use app\common\model\mall\StoreGoodsCategory;
use app\common\model\mall\StoreGoodsCoupon;
use think\Db;
use think\Exception;
use think\Log;
use think\Model;
use traits\model\SoftDelete;

class Store extends Model
{
    use SoftDelete;

    protected $name = 'store';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    // 追加属性
    protected $append = [
        'logo_image_url',
        'shop_door_image_url',
        'prove_images_url',
        'category_text',
    ];

    public function getLogoImageUrlAttr($value,$data)
    {
        return isset($data['logo_image']) && $data['logo_image'] ? cdnurl($data['logo_image'],true) : '';
    }

    public function getShopDoorImageUrlAttr($value,$data)
    {
        return isset($data['shop_door_image']) && $data['shop_door_image'] ? cdnurl($data['shop_door_image'],true) : '';
    }

    public function getProveImagesUrlAttr($value,$data)
    {
        return isset($data['prove_images']) && $data['prove_images'] ? cdnurl($data['prove_images'],true) : '';
    }

    public function getCategoryTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['category_ids']) ? $data['category_ids'] :'');
        $list = Category::where('id','in',$value)->column('name');
        return $list ? implode('、',$list) : '';
    }

    /**
     * 设置错误信息
     * @param $msg
     */
    public function setError($msg)
    {
        $this->error = $msg;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    public function category()
    {   //商品分类
        return $this->belongsToMany(Category::class,StoreGoodsCategory::class);
    }

    public function coupon()
    {   //商品分类
        return $this->belongsToMany(Coupon::class,StoreGoodsCoupon::class);
    }

    /**
     * 获取所有针对商家的收藏。
     */
    public function collect()
    {
        return $this->morphMany('Collect', 'type');
    }

    /**
     * 商家列表
     * @param array $where
     * @param int $limit            数量
     * @param int $page             页码
     * @param bool $pageStatus       是否分页   false：不分页   true  分页
     * @param array $extend       补充参数，如 lng经度、lat 纬度用于计算距离distance
     * @return void
     */
    public function list($where= [], $limit = 10, $page = null, $pageStatus = false,$extend = []){
        try {
            $limit = $limit ? $limit : 10;
            $page = $page ? $page : 1;
            $tempWhere = [
                'state' => ['=','20'],
            ];
            $field = 'id,shop_name,category_ids,logo_image,lng,lat';
            $where = array_merge($tempWhere,$where);
            $sql = self::alias('s')->where($where)
                ->order('weigh desc,total_sales desc')
                ->field($field);
            if($pageStatus){
                $list = $sql->paginate($limit,true,['page'=>$page])->each(function ($item){
                    $item->categoryArr = isset($item->category_text) ? explode('、',$item->category_text) : [];
                    if(!isset($item->distance)){
                        $item->distance = 0;
                    }
                    return $item;
                });
            }else{
                $list = $sql->select();
                if($list ){
                    foreach ($list as $k=>&$v){
                        $v['categoryArr'] = isset($v['category_text']) ? explode('、',$v['category_text']) : [];
                        if(!isset($v->distance)){
                            $v->distance = 0;
                        }
                    }
                }
            }
            return $list;
        }catch (Exception $e){
            Log::write('商家列表，SQL 语句：'.(new self())->getLastSql(),'log',true);
            $this->setError($e->getMessage());
            Log::write('商家列表，错误信息：'.$e->getMessage(),'error',true);
            return false;
        }
    }

    /**
     * 店铺详情
     * @param $store_id
     * @return void
     */
    public function details($store_id,$user_id = null){
        try {
            $store = self::get($store_id);
            if(empty($store)){
                $this->setError(__('No results were found'));
                return false;
            }
            $data = [
                'id' => $store->id,
                'shop_name' => $store->shop_name,
                'business_hours' => $store->business_hours,
                'address' => $store->address,
                'telephone' => $store->telephone,
                'categoryArr' => isset($store->category_text) ? explode('、',$store->category_text) : [],
                'logo_image_url' => $store->logo_image_url,
                'shop_door_image_url' => $store->shop_door_image_url,
                'coupon' => [],
                'goodsCategory' => [],
                'distance' => 0,
                'collect' => (bool)false,
            ];
            //优惠券
            if($store->coupon){
                foreach ($store->coupon as $k=>$v){
                    if($v->endtime > time()){
                        $temp = ['id' => $v->id,'title'=> $v->getData('title'),'endtime' => $v->endtime,'quantity'=>$v->quantity];
                        $data['coupon'][] = $temp;
                    }
                }
            }
            //array_unique  移除数组中重复的值
            $data['coupon'] = array_unique($data['coupon'], SORT_REGULAR);
            //二维数组，根据某字段排序
            array_multisort(array_column($data['coupon'],'endtime'), SORT_ASC, SORT_NUMERIC,$data['coupon']);
            //收藏
            if($user_id){
                $data['collect'] = (bool)Collect::where(['user_id'=>['=',$user_id],'type'=>['=','10'],'data_id'=>['=',$store_id]])->find();;
            }
            //商品分类
            if($store->category){
                foreach ($store->category as $k=>$v){
                    $data['goodsCategory'][] = ['id' => $v->id,'name'=> $v->getData('name'),'weigh'=>$v->weigh];
                }
            }
            //array_unique  移除数组中重复的值
            $data['goodsCategory'] = array_unique($data['goodsCategory'], SORT_REGULAR);
            //二维数组，根据某字段排序
            array_multisort(array_column($data['goodsCategory'],'weigh'), SORT_DESC, SORT_NUMERIC,$data['goodsCategory']);
            //距离
            $data['distance'] = 0;
            return $data;
        } catch (Exception $e) {
            $this->setError($e->getMessage());
            return false;
        }
    }

}